package com.system.shiro.session;

import java.io.Serializable;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.common.jedis.RedisManager;
import com.common.utils.SerializeUtils;

public class RedisSessionDao extends CachingSessionDAO {

    //过期时间默认30分钟
    private int expire = 1800;
    private static final int DB_INDEX=0;
    private static Logger logger = LoggerFactory.getLogger(RedisSessionDao.class);
    /**
     * The Redis key prefix for the sessions
     */
    private String keyPrefix = "shiro_redis_session:";

    private RedisManager redisManager;

    @Override
    protected void doUpdate(Session session) {
        //如果会话过期/停止 没必要再更新了
        if(session instanceof ValidatingSession && !((ValidatingSession)session).isValid()) {
            return;
        }
        redisManager.set(DB_INDEX,getByteKey(session.getId()), SerializeUtils.serialize(session),expire);
    }

    @Override
    protected void doDelete(Session session) {
        redisManager.del(DB_INDEX,getByteKey(session.getId()));
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        redisManager.set(DB_INDEX,getByteKey(sessionId), SerializeUtils.serialize(session),expire);
        return  session.getId();
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        if(sessionId == null){
            logger.error("session id is null");
            return null;
        }
        Session s = (Session) SerializeUtils.deserialize(redisManager.get(DB_INDEX,getByteKey(sessionId)));
        return s;
    }

    /**
     * 获得加上前缀后的bute类型的key
     * @param sessionId
     * @return
     */
    private byte[] getByteKey(Serializable sessionId){
        String preKey = this.keyPrefix + sessionId;
        return preKey.getBytes();
    }

    public void setRedisManager(RedisManager redisManager) {
        this.redisManager = redisManager;
    }

    public int getExpire() {
        return expire;
    }

    public void setExpire(int expire) {
        this.expire = expire;
    }
}
